package com.javafactroy.kunlong.bip.icp.netty.server.framework;

import com.javafactroy.kunlong.bip.icp.common.config.BipConfig;
import com.javafactroy.kunlong.bip.icp.common.consts.EAppType;
import com.javafactroy.kunlong.bip.icp.message.data.netty.codec.AppByte2MsgDecoder;
import com.javafactroy.kunlong.bip.icp.message.data.netty.codec.AppMsg2ByteEncoder;
import com.javafactroy.kunlong.bip.icp.message.data.netty.handler.server.BipServerHandler;
import com.javafactroy.kunlong.bip.icp.message.data.netty.handler.server.DataServerLengthFieldDecoder;
import com.javafactroy.kunlong.bip.icp.message.test.netty.codec.TMsgByte2MsgDecoder;
import com.javafactroy.kunlong.bip.icp.message.test.netty.codec.TMsgMsg2ByteEncoder;
import com.javafactroy.kunlong.bip.icp.message.test.netty.codec.TMsgServerLengthFieldDecoder;
import com.javafactroy.kunlong.bip.icp.message.test.netty.handler.server.TMsgServerHandler;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.net.InetSocketAddress;
import java.util.Properties;

@Component
@Slf4j
public class NettyServer {
    @Autowired
    BipConfig bipConfig;
    private int port;

    @Autowired
    BipServerHandler bipServerHandler;
    @Autowired
    TMsgServerHandler msgServerHandler;

    public NettyServer() {

    }

    public NettyServer(int port) {
        this.port = port;
    }

    public int getPort() {

        return port;
    }

    public void setPort(int port) {
        this.port = port;
    }

    class DxpChannelInitializer extends ChannelInitializer<SocketChannel> {

        @Override
        protected void initChannel(SocketChannel socketChannel) throws Exception {
            socketChannel.pipeline().addLast(
                    new DataServerLengthFieldDecoder(),
                    new AppByte2MsgDecoder(),
                    new AppMsg2ByteEncoder()).addLast(bipServerHandler);
        }
    }

    class TestChannelInitializer extends ChannelInitializer<SocketChannel> {

        @Override
        protected void initChannel(SocketChannel socketChannel) throws Exception {
            socketChannel.pipeline().addLast(
                    new TMsgServerLengthFieldDecoder(),
                    new TMsgMsg2ByteEncoder(),
                    new TMsgByte2MsgDecoder()).addLast(msgServerHandler);
        }
    }

    //@PostConstruct
    public void start(EAppType eAppType) throws Exception {
        if(bipConfig.getProps()==null){
            bipConfig.setProps(new Properties());
        }
        String sport = bipConfig.getProps().getProperty("server.port");
        setPort(Integer.valueOf(sport == null ? "6666" : sport));
        log.info("\n启动netty port = {}",getPort());

        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup)
                .channel(NioServerSocketChannel.class)
                .localAddress(new InetSocketAddress(port))
                .option(ChannelOption.SO_KEEPALIVE, true)
                .option(ChannelOption.TCP_NODELAY, true)
                .option(ChannelOption.SO_RCVBUF, 128000)
                .childHandler(eAppType.equals(EAppType.test) ?
                        new TestChannelInitializer() : new DxpChannelInitializer());
        log.info("\n启动 netty2");
        ChannelFuture channelFuture = b.bind().sync();
        if (channelFuture.isSuccess()) {
            log.info("启动成功! \nnetty server listen at :{}", port);
        }
        channelFuture.channel().closeFuture().addListener((r) -> {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        });

    }

}